<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/05/20
 */
namespace console\controllers;

use GuzzleHttp\Client;
use yii;
use yii\console\Controller;

set_time_limit(0);

class ExchangeController extends Controller {
    public $baseHeader = [
        'Accept' => '*/*',
        'Accept-Language' => 'zh',
        'Accept-Encoding' => 'gzip, deflate',
        'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        //'Cookie' => self::COOKIE,
        //'Host' => 'divebooker.com',
        'Connection' => 'keep-alive',
    ];

    public function actionRateUpdate() {
        $c = new Client();
        $r = $c->get('http://quoteapi.webull.sec.miui.com/api/quote/market/mi/foreignExchangesRates', [
            'headers' => array_merge($this->baseHeader, [
                'Referer' => 'quoteapi.webull.sec.miui.com',
            ]),
        ]);
        $res = json_decode($r->getBody(), true);
        if (!$res || empty($res['rate'])) {
            Yii::error((string)$r->getBody(), __METHOD__);
            return;
        }
        $need = [
            'USD',
            'CNY',
            'EUR'
        ];
        $map = [];
        foreach ($res['rate'] as $item) {
            if (in_array($item['n1'], $need) && in_array($item['n2'], $need)) {
                $map[$item['n1']][$item['n2']] = $item['r'];
            }
        }
        file_put_contents(Yii::$app->params['env']['DATA_PATH'] . 'exchange-rate.php', '<?php return ' . var_export($map, true) . ';');
        echo date('Y-m-d H:i:s') . '|' . json_encode($map, true) . "\n";
    }
}